<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>个人中心 - 探索世界</title>
  <style>
    /* 样式保持不变 */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Helvetica Neue', Arial, sans-serif;
    }

    body {
      background-color: #f8f9fa;
      color: #333;
      line-height: 1.6;
    }

    a {
      text-decoration: none;
      color: inherit;
    }

    ul {
      list-style: none;
    }

    .container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 15px;
    }

    .btn {
      display: inline-block;
      padding: 10px 20px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;
    }

    .btn:hover {
      background-color: #45a049;
    }

    .btn-outline {
      background-color: transparent;
      color: #4CAF50;
      border: 1px solid #4CAF50;
    }

    .btn-outline:hover {
      background-color: #4CAF50;
      color: white;
    }

    .btn-danger {
      background-color: #dc3545;
    }

    .btn-danger:hover {
      background-color: #c82333;
    }

    .section-title {
      text-align: center;
      margin-bottom: 30px;
      font-size: 28px;
      color: #2c3e50;
      position: relative;
      padding-bottom: 15px;
    }

    .section-title:after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 80px;
      height: 3px;
      background-color: #4CAF50;
    }
    /* 密码强度指示器 */
    .password-strength {
      margin-top: 5px;
      height: 5px;
      border-radius: 2px;
      background-color: #eee;
      overflow: hidden;
    }

    .password-strength-bar {
      height: 100%;
      width: 0%;
      transition: width 0.3s, background-color 0.3s;
    }

    .password-requirements {
      margin-top: 5px;
      font-size: 12px;
      color: #666;
    }

    .requirement {
      display: flex;
      align-items: center;
      margin-bottom: 3px;
    }

    .requirement.valid {
      color: #4CAF50;
    }

    .requirement.invalid {
      color: #dc3545;
    }

    .requirement i {
      margin-right: 5px;
      font-size: 10px;
    }

    /* 头部样式 */
    header {
      background-color: white;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      position: sticky;
      top: 0;
      z-index: 1000;
    }

    .header-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 0;
    }

    .logo {
      font-size: 24px;
      font-weight: bold;
      color: #4CAF50;
    }

    .logo span {
      color: #2c3e50;
    }

    nav ul {
      display: flex;
    }

    nav ul li {
      margin-left: 20px;
    }

    nav ul li a {
      padding: 5px 10px;
      transition: color 0.3s;
    }

    nav ul li a:hover {
      color: #4CAF50;
    }

    .auth-buttons {
      display: flex;
      gap: 10px;
    }

    .auth-buttons .btn {
      padding: 8px 15px;
    }

    .btn-login {
      background-color: transparent;
      color: #4CAF50;
      border: 1px solid #4CAF50;
    }

    .btn-login:hover {
      background-color: #4CAF50;
      color: white;
    }

    /* 个人中心内容样式 */
    .profile-section {
      padding: 60px 0;
    }

    .profile-container {
      display: grid;
      grid-template-columns: 300px 1fr;
      gap: 30px;
    }

    .profile-sidebar {
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      padding: 20px;
      height: fit-content;
    }

    .user-info {
      text-align: center;
      margin-bottom: 20px;
    }

    .user-avatar {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      overflow: hidden;
      margin: 0 auto 15px;
      border: 3px solid #f1f8e9;
    }

    .user-avatar img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .user-name {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 5px;
    }

    .user-level {
      color: #4CAF50;
      font-size: 14px;
    }

    .profile-menu ul li {
      margin-bottom: 10px;
    }

    .profile-menu ul li a {
      display: block;
      padding: 12px 15px;
      border-radius: 4px;
      transition: background-color 0.3s;
    }

    .profile-menu ul li a:hover,
    .profile-menu ul li a.active {
      background-color: #f1f8e9;
      color: #4CAF50;
    }

    .profile-menu ul li a i {
      margin-right: 10px;
      width: 20px;
      text-align: center;
    }

    .profile-content {
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      padding: 30px;
    }

    .profile-tab {
      display: none;
    }

    .profile-tab.active {
      display: block;
    }

    .form-group {
      margin-bottom: 20px;
    }

    .form-group label {
      display: block;
      margin-bottom: 8px;
      font-weight: bold;
      color: #2c3e50;
    }

    .form-control {
      width: 100%;
      padding: 12px 15px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 16px;
      transition: border-color 0.3s;
    }

    .form-control:focus {
      border-color: #4CAF50;
      outline: none;
    }

    .form-row {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 15px;
    }

    /* 我的作品样式 */
    .works-container {
      margin-top: 20px;
    }

    .works-section {
      margin-bottom: 30px;
    }

    .works-section h4 {
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
      color: #2c3e50;
    }

    .works-section h4 i {
      margin-right: 10px;
      color: #4CAF50;
    }

    .works-list {
      min-height: 100px;
    }

    .work-item {
      display: flex;
      padding: 15px;
      border: 1px solid #eee;
      border-radius: 4px;
      margin-bottom: 15px;
      transition: box-shadow 0.3s;
      cursor: pointer;
    }

    .work-item:hover {
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }

    .work-image {
      width: 120px;
      height: 80px;
      border-radius: 4px;
      overflow: hidden;
      margin-right: 15px;
      flex-shrink: 0;
    }

    .work-image img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .work-content {
      flex: 1;
    }

    .work-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 8px;
      color: #2c3e50;
    }

    .work-meta {
      display: flex;
      font-size: 13px;
      color: #666;
      margin-bottom: 8px;
    }

    .work-meta span {
      margin-right: 15px;
    }

    .work-stats {
      display: flex;
      font-size: 13px;
      color: #666;
    }

    .work-stats span {
      margin-right: 15px;
    }

    .work-excerpt {
      font-size: 14px;
      color: #666;
      margin-top: 8px;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .empty-state {
      text-align: center;
      padding: 30px 0;
      color: #999;
    }

    .empty-state i {
      font-size: 48px;
      margin-bottom: 15px;
      color: #ddd;
    }

    .loading {
      text-align: center;
      padding: 30px 0;
    }

    .loading-spinner {
      border: 3px solid #f3f3f3;
      border-top: 3px solid #4CAF50;
      border-radius: 50%;
      width: 30px;
      height: 30px;
      animation: spin 1s linear infinite;
      margin: 0 auto 15px;
    }

    /* 修改密码步骤样式 */
    .password-change-steps {
      display: flex;
      justify-content: space-between;
      margin-bottom: 30px;
      position: relative;
    }

    .password-change-steps:before {
      content: '';
      position: absolute;
      top: 15px;
      left: 0;
      right: 0;
      height: 2px;
      background-color: #e0e0e0;
      z-index: 1;
    }

    .step {
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      z-index: 2;
      flex: 1;
    }

    .step-circle {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background-color: #e0e0e0;
      color: #999;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 8px;
      font-weight: bold;
    }

    .step.active .step-circle {
      background-color: #4CAF50;
      color: white;
    }

    .step.completed .step-circle {
      background-color: #4CAF50;
      color: white;
    }

    .step.completed .step-circle:after {
      content: '\f00c';
      font-family: 'Font Awesome 5 Free';
      font-weight: 900;
    }

    .step-label {
      font-size: 14px;
      color: #999;
      text-align: center;
    }

    .step.active .step-label {
      color: #4CAF50;
      font-weight: bold;
    }

    .step.completed .step-label {
      color: #4CAF50;
    }

    .step-content {
      display: none;
    }

    .step-content.active {
      display: block;
    }

    .step-actions {
      display: flex;
      justify-content: space-between;
      margin-top: 30px;
    }

    .verification-code-group {
      display: flex;
      gap: 10px;
    }

    .verification-code-group .form-control {
      flex: 1;
    }

    .btn-get-code {
      white-space: nowrap;
      min-width: 120px;
    }

    .btn-get-code:disabled {
      background-color: #cccccc;
      cursor: not-allowed;
    }

    /* 模态框样式 */
    .modal {
      display: none;
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
    }

    .modal-content {
      background-color: white;
      margin: 10% auto;
      padding: 30px;
      border-radius: 8px;
      width: 50%;
      max-width: 600px;
    }

    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }

    .close {
      font-size: 24px;
      cursor: pointer;
    }

    /* 响应式设计 */
    @media (max-width: 992px) {
      .profile-container {
        grid-template-columns: 1fr;
      }

      .profile-sidebar {
        margin-bottom: 20px;
      }

      .form-row {
        grid-template-columns: 1fr;
      }

      .modal-content {
        width: 80%;
      }
    }

    @media (max-width: 768px) {
      .header-container {
        flex-direction: column;
      }

      nav ul {
        margin: 15px 0;
      }

      .modal-content {
        width: 95%;
        margin: 5% auto;
      }

      .action-buttons {
        flex-direction: column;
      }

      .password-change-steps {
        flex-direction: column;
        align-items: flex-start;
      }

      .password-change-steps:before {
        display: none;
      }

      .step {
        flex-direction: row;
        margin-bottom: 15px;
        width: 100%;
      }

      .step-circle {
        margin-right: 10px;
        margin-bottom: 0;
      }
    }

    /* 加载动画 */
    .loading {
      display: inline-block;
      width: 20px;
      height: 20px;
      border: 3px solid #f3f3f3;
      border-top: 3px solid #4CAF50;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .toast {
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 15px 20px;
      background-color: #4CAF50;
      color: white;
      border-radius: 4px;
      z-index: 1000;
      opacity: 0;
      transform: translateY(-20px);
      transition: opacity 0.3s, transform 0.3s;
    }

    .toast.show {
      opacity: 1;
      transform: translateY(0);
    }

    .toast.error {
      background-color: #dc3545;
    }
  </style>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
<!-- 头部导航 -->
<header>
  <div class="container header-container">
    <div class="logo">
      <a href="index.html">探索<span>世界</span></a>
    </div>
    <nav>
      <ul>
        <li><a href="index.html">首页</a></li>
        <li><a href="scenic.html">景区</a></li>
        <li><a href="dot.html">景点</a></li>
        <li><a href="order.html">订单</a></li>
        <li><a href="guide.html">攻略</a></li>
        <li><a href="notes.html" style="color: #4CAF50;">游记</a></li>
      </ul>
    </nav>
    <div class="auth-buttons" id="authButtons">
      <!-- 登录状态由JavaScript动态生成 -->
    </div>
  </div>
</header>

<!-- 个人中心内容 -->
<section class="profile-section">
  <div class="container">
    <h2 class="section-title">个人中心</h2>
    <div class="profile-container">
      <!-- 侧边栏 -->
      <div class="profile-sidebar">
        <div class="user-info">
          <div class="user-avatar">
            <img src="https://source.unsplash.com/300x300/?person" alt="用户头像" id="userAvatar">
          </div>
          <div class="user-name" id="userName">加载中...</div>
          <div class="user-level" id="userLevel">会员</div>
        </div>
        <div class="profile-menu">
          <ul>
            <li><a href="#personal" class="active" onclick="switchTab('personal')"><i class="fas fa-user"></i> 个人信息</a></li>
            <li><a href="#bookings" onclick="switchTab('bookings')"><i class="fas fa-ticket-alt"></i> 我的行程</a></li>
            <li><a href="#favorites" onclick="switchTab('favorites')"><i class="fas fa-heart"></i> 我的收藏</a></li>
            <li><a href="#works" onclick="switchTab('works')"><i class="fas fa-book"></i> 我的作品</a></li>
            <li><a href="#security" onclick="switchTab('security')"><i class="fas fa-lock"></i> 账户安全</a></li>
            <!-- 添加退出登录选项 -->
            <li><a href="#" onclick="logout()"><i class="fas fa-sign-out-alt"></i> 退出登录</a></li>
          </ul>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="profile-content">
        <!-- 个人信息标签页 -->
        <div id="personal" class="profile-tab active">
          <h3>个人信息</h3>
          <form id="profileForm">
            <div class="form-row">
              <div class="form-group">
                <label for="visitorsName">游客名称</label>
                <input type="text" id="visitorsName" class="form-control" readonly>
              </div>
              <div class="form-group">
                <label for="realName">真实姓名</label>
                <input type="text" id="realName" class="form-control">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label for="gender">性别</label>
                <select id="gender" class="form-control">
                  <option value="1">男</option>
                  <option value="2">女</option>
                  <option value="0">未设置</option>
                </select>
              </div>
              <div class="form-group">
                <label for="phoneNumber">手机号码</label>
                <input type="tel" id="phoneNumber" class="form-control">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label for="email">邮箱地址</label>
                <input type="email" id="email" class="form-control">
              </div>
              <div class="form-group">
                <label for="idCard">身份证号</label>
                <input type="text" id="idCard" class="form-control">
              </div>
            </div>
            <div class="form-group">
              <label for="birthday">出生日期</label>
              <input type="date" id="birthday" class="form-control">
            </div>
            <div class="form-group">
              <label for="avatar">头像</label>
              <input type="file" id="avatar" class="form-control" accept="image/*">
            </div>
            <button type="button" class="btn" onclick="saveProfile()" id="saveProfileBtn">
              <span id="saveProfileText">保存修改</span>
              <span class="loading" id="saveProfileLoading" style="display: none;"></span>
            </button>
          </form>
        </div>

        <!-- 我的行程标签页 -->
        <div id="bookings" class="profile-tab">
          <h3>我的行程</h3>
          <p>这里将显示您的行程信息。</p>
        </div>

        <!-- 我的收藏标签页 -->
        <div id="favorites" class="profile-tab">
          <h3>我的收藏</h3>
          <p>这里将显示您收藏的景点、攻略和游记。</p>
        </div>

        <!-- 我的作品标签页 -->
        <div id="works" class="profile-tab">
          <h3>我的作品</h3>
          <div class="works-container">
            <div class="works-section">
              <h4><i class="fas fa-map"></i> 我的攻略</h4>
              <div id="guides-list" class="works-list">
                <div class="loading" id="guides-loading">
                  <div class="loading-spinner"></div>
                  <p>加载中...</p>
                </div>
                <div class="empty-state" id="guides-empty" style="display: none;">
                  <i class="fas fa-map-marked-alt"></i>
                  <p>暂无发布的攻略</p>
                </div>
                <!-- 攻略列表将通过JavaScript动态加载 -->
              </div>
            </div>
            
            <div class="works-section">
              <h4><i class="fas fa-book-open"></i> 我的游记</h4>
              <div id="notes-list" class="works-list">
                <div class="loading" id="notes-loading">
                  <div class="loading-spinner"></div>
                  <p>加载中...</p>
                </div>
                <div class="empty-state" id="notes-empty" style="display: none;">
                  <i class="fas fa-book"></i>
                  <p>暂无发布的游记</p>
                </div>
                <!-- 游记列表将通过JavaScript动态加载 -->
              </div>
            </div>
          </div>
        </div>

        <!-- 账户安全标签页 -->
        <div id="security" class="profile-tab">
          <h3>账户安全</h3>

          <!-- 修改密码步骤 -->
          <div class="password-change-steps">
            <div class="step active" id="step1">
              <div class="step-circle">1</div>
              <div class="step-label">验证手机号</div>
            </div>
            <div class="step" id="step2">
              <div class="step-circle">2</div>
              <div class="step-label">验证验证码</div>
            </div>
            <div class="step" id="step3">
              <div class="step-circle">3</div>
              <div class="step-label">设置新密码</div>
            </div>
          </div>

          <!-- 步骤1：验证手机号 -->
          <div id="step1-content" class="step-content active">
            <div class="form-group">
              <label for="phoneForVerification">手机号码</label>
              <input type="tel" id="phoneForVerification" class="form-control" placeholder="请输入手机号码">
              <div id="phoneError" style="color: #dc3545; font-size: 12px; margin-top: 5px; display: none;"></div>
            </div>
            <div class="step-actions">
              <div></div> <!-- 占位 -->
              <button class="btn" onclick="sendVerificationCode()" id="sendCodeBtn">
                <span id="sendCodeText">发送验证码</span>
                <span class="loading" id="sendCodeLoading" style="display: none;"></span>
              </button>
            </div>
          </div>

          <!-- 步骤2：验证验证码 -->
          <div id="step2-content" class="step-content">
            <div class="form-group">
              <label for="verificationCode">验证码</label>
              <div class="verification-code-group">
                <input type="text" id="verificationCode" class="form-control" placeholder="请输入验证码">
                <button class="btn btn-outline btn-get-code" onclick="sendVerificationCode()" id="resendCodeBtn" disabled>
                  <span id="resendCodeText">重新发送(60)</span>
                </button>
              </div>
              <div id="codeError" style="color: #dc3545; font-size: 12px; margin-top: 5px; display: none;"></div>
            </div>
            <div class="step-actions">
              <button class="btn btn-outline" onclick="previousStep(2)">上一步</button>
              <button class="btn" onclick="verifyCode()" id="verifyCodeBtn">
                <span id="verifyCodeText">验证</span>
                <span class="loading" id="verifyCodeLoading" style="display: none;"></span>
              </button>
            </div>
          </div>

          <!-- 步骤3：设置新密码 -->
          <div id="step3-content" class="step-content">
            <div class="form-group">
              <label for="currentPassword">当前密码</label>
              <input type="password" id="currentPassword" class="form-control" placeholder="请输入当前密码">
              <div id="currentPasswordError" style="color: #dc3545; font-size: 12px; margin-top: 5px; display: none;"></div>
            </div>
            <div class="form-group">
              <label for="newPassword">新密码</label>
              <input type="password" id="newPassword" class="form-control" placeholder="请输入新密码" oninput="validatePassword()">
              <div class="password-strength">
                <div class="password-strength-bar" id="passwordStrengthBar"></div>
              </div>
              <div class="password-requirements">
                <div class="requirement" id="lengthReq">
                  <i class="fas fa-circle"></i> 长度6-20位
                </div>
                <div class="requirement" id="letterReq">
                  <i class="fas fa-circle"></i> 包含字母
                </div>
                <div class="requirement" id="numberReq">
                  <i class="fas fa-circle"></i> 包含数字
                </div>
              </div>
            </div>
            <div class="form-group">
              <label for="confirmPassword">确认新密码</label>
              <input type="password" id="confirmPassword" class="form-control" placeholder="请再次输入新密码" oninput="checkPasswordMatch()">
              <div id="confirmPasswordError" style="color: #dc3545; font-size: 12px; margin-top: 5px; display: none;"></div>
            </div>
            <div class="step-actions">
              <button class="btn btn-outline" onclick="previousStep(3)">上一步</button>
              <button class="btn" onclick="changePassword()" id="changePasswordBtn">
                <span id="changePasswordText">修改密码</span>
                <span class="loading" id="changePasswordLoading" style="display: none;"></span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- Toast提示 -->
<div id="toast" class="toast"></div>

<script>
  const API_BASE = 'http://localhost:17112/visitors';
  let currentUser = null;
  let countdownTimer = null;
  let countdownSeconds = 60;

  // 显示Toast提示
  function showToast(message, isError = false) {
    const toast = document.getElementById('toast');
    toast.textContent = message;
    toast.className = isError ? 'toast error show' : 'toast show';

    setTimeout(() => {
      toast.className = 'toast';
    }, 3000);
  }

  // 切换标签页
  function switchTab(tabId) {
    document.querySelectorAll('.profile-tab').forEach(tab => {
      tab.classList.remove('active');
    });
    document.querySelectorAll('.profile-menu a').forEach(link => {
      link.classList.remove('active');
    });

    document.getElementById(tabId).classList.add('active');
    document.querySelector(`a[href="#${tabId}"]`).classList.add('active');

    // 如果是账户安全标签页，重置修改密码流程
    if (tabId === 'security') {
      resetPasswordChangeProcess();
    }
  }

  // 重置修改密码流程
  function resetPasswordChangeProcess() {
    // 重置步骤
    document.querySelectorAll('.step').forEach((step, index) => {
      if (index === 0) {
        step.classList.add('active');
        step.classList.remove('completed');
      } else {
        step.classList.remove('active', 'completed');
      }
    });

    // 重置内容
    document.querySelectorAll('.step-content').forEach((content, index) => {
      if (index === 0) {
        content.classList.add('active');
      } else {
        content.classList.remove('active');
      }
    });

    // 清空表单
    document.getElementById('phoneForVerification').value = '';
    document.getElementById('verificationCode').value = '';
    document.getElementById('currentPassword').value = '';
    document.getElementById('newPassword').value = '';
    document.getElementById('confirmPassword').value = '';

    // 重置错误提示
    document.getElementById('phoneError').style.display = 'none';
    document.getElementById('codeError').style.display = 'none';
    document.getElementById('currentPasswordError').style.display = 'none';
    document.getElementById('confirmPasswordError').style.display = 'none';

    // 重置密码强度指示器
    validatePassword();

    // 重置倒计时
    if (countdownTimer) {
      clearInterval(countdownTimer);
      countdownTimer = null;
    }
    document.getElementById('resendCodeBtn').disabled = true;
    document.getElementById('resendCodeText').textContent = '重新发送(60)';
    countdownSeconds = 60;
  }

  // 加载当前用户信息
  async function loadCurrentUser() {
    try {
      const cid = localStorage.getItem('cid');
      const userInfoStr = localStorage.getItem('userInfo');

      console.log('CID from localStorage:', cid);
      console.log('UserInfo from localStorage:', userInfoStr);

      // 如果本地有用户信息，先显示出来
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr);
          currentUser = userInfo;
          updateUserProfile(userInfo);
          console.log('Loaded from localStorage:', userInfo);
        } catch (e) {
          console.error('解析用户信息失败:', e);
        }
      }

      if (!cid) {
        console.error('未找到用户ID，重定向到登录页面');
        window.location.href = 'login.html';
        return;
      }

      // 总是从API获取最新数据
      console.log('Fetching user data from API...');
      const response = await fetch(`${API_BASE}/queryById?visitorId=${cid}`);
      console.log('API response status:', response.status);

      if (response.ok) {
        const result = await response.json();
        console.log('API response data:', result);

        if (result.code === 200) {
          currentUser = result.data;
          // 保存用户信息到本地存储
          localStorage.setItem('userInfo', JSON.stringify(result.data));
          updateUserProfile(currentUser);
          console.log('User data updated from API');
        } else {
          console.error('获取用户信息失败:', result.message);
          showToast('获取用户信息失败: ' + result.message, true);
        }
      } else {
        console.error('网络请求失败，状态码:', response.status);
        showToast('网络请求失败，状态码: ' + response.status, true);
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
      showToast('加载用户信息失败: ' + error.message, true);
    }
  }

  // 更新用户界面
  function updateUserProfile(user) {
    if (!user) {
      console.error('用户数据为空');
      return;
    }

    console.log('Updating profile with:', user);

    // 设置表单值
    document.getElementById('visitorsName').value = user.visitorsName || '';
    document.getElementById('realName').value = user.realName || '';
    document.getElementById('gender').value = user.gender || '0';
    document.getElementById('phoneNumber').value = user.phoneNumber || '';
    document.getElementById('email').value = user.email || '';
    document.getElementById('idCard').value = user.idCard || '';

    // 处理日期格式
    let birthdayValue = '';
    if (user.birthday) {
      if (typeof user.birthday === 'string') {
        // 处理不同的日期格式
        if (user.birthday.includes('T')) {
          birthdayValue = user.birthday.split('T')[0];
        } else if (user.birthday.includes(' ')) {
          birthdayValue = user.birthday.split(' ')[0];
        } else {
          birthdayValue = user.birthday;
        }
      } else if (user.birthday instanceof Date) {
        birthdayValue = user.birthday.toISOString().split('T')[0];
      }
    }
    document.getElementById('birthday').value = birthdayValue;

    // 更新显示信息
    document.getElementById('userName').textContent = user.visitorsName || user.realName || '用户';
    document.getElementById('userLevel').textContent = 'VIP会员';

    // 设置头像
    if (user.avatar) {
      // 确保头像URL是完整的
      let avatarUrl = user.avatar;
      if (!avatarUrl.startsWith('http') && !avatarUrl.startsWith('/')) {
        avatarUrl = '/' + avatarUrl;
      }
      document.getElementById('userAvatar').src = avatarUrl;
    } else {
      // 使用默认头像
      document.getElementById('userAvatar').src = 'https://source.unsplash.com/300x300/?person';
    }

    console.log('Profile updated successfully');
  }

  // 保存个人信息
  async function saveProfile() {
    const saveBtn = document.getElementById('saveProfileBtn');
    const loading = document.getElementById('saveProfileLoading');
    const text = document.getElementById('saveProfileText');
    const avatarFile = document.getElementById('avatar').files[0];

    try {
      saveBtn.disabled = true;
      loading.style.display = 'inline-block';
      text.textContent = '保存中...';

      let avatarUrl = currentUser.avatar || '';

      // 如果有新头像文件，先上传头像
      if (avatarFile) {
        const uploadedUrl = await uploadAvatar(avatarFile, currentUser.visitorId);
        if (uploadedUrl) {
          avatarUrl = uploadedUrl;
        }
      }

      const userData = {
        visitorId: currentUser.visitorId,
        visitorsName: document.getElementById('visitorsName').value,
        realName: document.getElementById('realName').value,
        gender: parseInt(document.getElementById('gender').value),
        phoneNumber: document.getElementById('phoneNumber').value,
        email: document.getElementById('email').value,
        idCard: document.getElementById('idCard').value,
        birthday: document.getElementById('birthday').value,
        avatar: avatarUrl
      };

      console.log('Saving user data:', userData);

      const response = await fetch(`${API_BASE}/update`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(userData)
      });

      console.log('Save response status:', response.status);

      if (response.ok) {
        const result = await response.json();
        console.log('Save response data:', result);

        if (result.code === 200) {
          showToast('个人信息保存成功');
          await loadCurrentUser(); // 重新加载用户信息
          document.getElementById('avatar').value = ''; // 清空文件选择
        } else {
          showToast('保存失败: ' + result.message, true);
        }
      } else {
        const errorText = await response.text();
        console.error('Save error:', errorText);
        showToast('保存失败: 网络请求错误 - ' + response.status, true);
      }
    } catch (error) {
      console.error('保存失败:', error);
      showToast('保存失败: ' + error.message, true);
    } finally {
      saveBtn.disabled = false;
      loading.style.display = 'none';
      text.textContent = '保存修改';
    }
  }

  // 上传头像
  async function uploadAvatar(file, visitorId) {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('visitorId', visitorId);

      const response = await fetch(`${API_BASE}/uploadAvatar`, {
        method: 'POST',
        body: formData
      });

      if (response.ok) {
        const result = await response.json();
        if (result.code === 200) {
          showToast('头像上传成功');
          return result.data.url; // 返回文件URL
        } else {
          showToast('头像上传失败: ' + result.message, true);
          return null;
        }
      } else {
        showToast('头像上传失败: 网络请求错误', true);
        return null;
      }
    } catch (error) {
      console.error('头像上传失败:', error);
      showToast('头像上传失败', true);
      return null;
    }
  }

  // 密码强度验证
  function validatePassword() {
    const password = document.getElementById('newPassword').value;
    const strengthBar = document.getElementById('passwordStrengthBar');
    const lengthReq = document.getElementById('lengthReq');
    const letterReq = document.getElementById('letterReq');
    const numberReq = document.getElementById('numberReq');

    // 重置状态
    strengthBar.style.width = '0%';
    strengthBar.style.backgroundColor = '#dc3545';
    lengthReq.className = 'requirement invalid';
    letterReq.className = 'requirement invalid';
    numberReq.className = 'requirement invalid';

    if (password.length === 0) return;

    let strength = 0;

    // 检查长度
    if (password.length >= 6 && password.length <= 20) {
      strength += 33;
      lengthReq.className = 'requirement valid';
    }

    // 检查是否包含字母
    if (/[a-zA-Z]/.test(password)) {
      strength += 33;
      letterReq.className = 'requirement valid';
    }

    // 检查是否包含数字
    if (/\d/.test(password)) {
      strength += 34;
      numberReq.className = 'requirement valid';
    }

    // 更新强度条
    strengthBar.style.width = strength + '%';

    if (strength < 66) {
      strengthBar.style.backgroundColor = '#dc3545';
    } else if (strength < 100) {
      strengthBar.style.backgroundColor = '#ffc107';
    } else {
      strengthBar.style.backgroundColor = '#28a745';
    }
  }

  // 检查密码是否匹配
  function checkPasswordMatch() {
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    const errorDiv = document.getElementById('confirmPasswordError');

    if (confirmPassword.length > 0 && newPassword !== confirmPassword) {
      errorDiv.textContent = '两次输入的密码不一致';
      errorDiv.style.display = 'block';
    } else {
      errorDiv.style.display = 'none';
    }
  }

  // 发送验证码
  async function sendVerificationCode() {
    const phone = document.getElementById('phoneForVerification').value;
    const phoneError = document.getElementById('phoneError');
    const sendBtn = document.getElementById('sendCodeBtn');
    const loading = document.getElementById('sendCodeLoading');
    const text = document.getElementById('sendCodeText');
    const resendBtn = document.getElementById('resendCodeBtn');

    // 验证手机号
    if (!phone) {
      phoneError.textContent = '请输入手机号码';
      phoneError.style.display = 'block';
      return;
    }

    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      phoneError.textContent = '手机号码格式不正确';
      phoneError.style.display = 'block';
      return;
    }

    phoneError.style.display = 'none';

    try {
      sendBtn.disabled = true;
      loading.style.display = 'inline-block';
      text.textContent = '发送中...';

      // 调用发送验证码接口
      const response = await fetch('/auth/sendCode', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `phoneNumber=${encodeURIComponent(phone)}`
      });

      const result = await response.json();

      if (result.success) {
        showToast('验证码已发送，请注意查收');

        // 启动倒计时
        startCountdown();
        
        // 跳转到下一步（验证验证码步骤）
        nextStep(1);
      } else {
        showToast('发送验证码失败: ' + result.message, true);
      }
    } catch (error) {
      console.error('发送验证码失败:', error);
      showToast('发送验证码失败: ' + error.message, true);
    } finally {
      sendBtn.disabled = false;
      loading.style.display = 'none';
      text.textContent = '发送验证码';
    }
  }

  // 启动倒计时
  function startCountdown() {
    const resendBtn = document.getElementById('resendCodeBtn');
    const resendText = document.getElementById('resendCodeText');
    
    resendBtn.disabled = true;
    countdownSeconds = 60;
    
    resendText.textContent = `重新发送(${countdownSeconds})`;
    
    countdownTimer = setInterval(() => {
      countdownSeconds--;
      resendText.textContent = `重新发送(${countdownSeconds})`;
      
      if (countdownSeconds <= 0) {
        clearInterval(countdownTimer);
        resendBtn.disabled = false;
        resendText.textContent = '重新发送';
      }
    }, 1000);
  }

  // 验证验证码
  async function verifyCode() {
    const phone = document.getElementById('phoneForVerification').value;
    const code = document.getElementById('verificationCode').value;
    const codeError = document.getElementById('codeError');
    const verifyBtn = document.getElementById('verifyCodeBtn');
    const loading = document.getElementById('verifyCodeLoading');
    const text = document.getElementById('verifyCodeText');

    if (!code) {
      codeError.textContent = '请输入验证码';
      codeError.style.display = 'block';
      return;
    }

    const codeRegex = /^\d{6}$/;
    if (!codeRegex.test(code)) {
      codeError.textContent = '验证码为6位数字';
      codeError.style.display = 'block';
      return;
    }

    codeError.style.display = 'none';

    try {
      verifyBtn.disabled = true;
      loading.style.display = 'inline-block';
      text.textContent = '验证中...';

      // 调用验证验证码接口
      const response = await fetch('/auth/verifyCode', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `phoneNumber=${encodeURIComponent(phone)}&code=${encodeURIComponent(code)}`
      });

      const result = await response.json();

      if (result.success) {
        showToast('验证码验证成功');

        // 跳转到下一步
        nextStep(2);
      } else {
        showToast('验证码错误，请重新输入', true);
      }
    } catch (error) {
      console.error('验证码验证失败:', error);
      showToast('验证码验证失败: ' + error.message, true);
    } finally {
      verifyBtn.disabled = false;
      loading.style.display = 'none';
      text.textContent = '验证';
    }
  }

  // 修改密码
  async function changePassword() {
    const phone = document.getElementById('phoneForVerification').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    const confirmPasswordError = document.getElementById('confirmPasswordError');
    const changeBtn = document.getElementById('changePasswordBtn');
    const loading = document.getElementById('changePasswordLoading');
    const text = document.getElementById('changePasswordText');

    // 密码验证
    if (!validatePasswordForChange(newPassword)) {
      return;
    }

    // 确认密码验证
    if (newPassword !== confirmPassword) {
      confirmPasswordError.textContent = '两次输入的密码不一致';
      confirmPasswordError.style.display = 'block';
      return;
    } else {
      confirmPasswordError.style.display = 'none';
    }

    try {
      changeBtn.disabled = true;
      loading.style.display = 'inline-block';
      text.textContent = '修改中...';

      // 调用修改密码接口
      const response = await fetch('/visitors/resetPassword', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          phoneNumber: phone,
          newPassword: newPassword
        })
      });

      const result = await response.json();

      if (result.code === 200) {
        showToast('密码修改成功，请重新登录');

        // 重置修改密码流程
        resetPasswordChangeProcess();

        // 延迟跳转到登录页面
        setTimeout(() => {
          logout();
        }, 1500);
      } else {
        showToast(result.message || '密码修改失败，请稍后重试', true);
      }
    } catch (error) {
      console.error('密码修改失败:', error);
      showToast('密码修改失败: ' + error.message, true);
    } finally {
      changeBtn.disabled = false;
      loading.style.display = 'none';
      text.textContent = '修改密码';
    }
  }
  
  // 密码验证函数
  function validatePasswordForChange(password) {
    // 检查是否为空
    if (!password) {
      showToast('请输入新密码', true);
      return false;
    }
    
    // 检查长度
    if (password.length < 6 || password.length > 20) {
      showToast('密码长度需在6-20位', true);
      return false;
    }

    // 检查是否包含数字和字母
    const hasNumber = /\d/.test(password);
    const hasLetter = /[a-zA-Z]/.test(password);

    if (!hasNumber || !hasLetter) {
      showToast('密码必须包含数字和字母', true);
      return false;
    }

    return true;
  }

  // 下一步
  function nextStep(currentStep) {
    // 标记当前步骤为已完成
    document.getElementById(`step${currentStep}`).classList.remove('active');
    document.getElementById(`step${currentStep}`).classList.add('completed');

    // 显示下一步
    document.getElementById(`step${currentStep + 1}`).classList.add('active');

    // 切换内容
    document.getElementById(`step${currentStep}-content`).classList.remove('active');
    document.getElementById(`step${currentStep + 1}-content`).classList.add('active');
  }

  // 上一步
  function previousStep(currentStep) {
    // 标记当前步骤为未完成
    document.getElementById(`step${currentStep}`).classList.remove('active');
    document.getElementById(`step${currentStep - 1}`).classList.remove('completed');
    document.getElementById(`step${currentStep - 1}`).classList.add('active');

    // 切换内容
    document.getElementById(`step${currentStep}-content`).classList.remove('active');
    document.getElementById(`step${currentStep - 1}-content`).classList.add('active');
  }

  // 退出登录
  function logout() {
    if (confirm('确定要退出登录吗？')) {
      localStorage.removeItem('cid');
      localStorage.removeItem('userInfo');
      window.location.href = 'login.html';
    }
  }

  // 页面加载完成后初始化
  document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    const cid = localStorage.getItem('cid');
    if (!cid) {
      window.location.href = 'login.html';
      return;
    }

    // 加载用户信息
    loadCurrentUser();
    
    // 加载用户作品
    loadUserWorks();

    // 初始化密码强度指示器
    validatePassword();
  });
  
  // 加载用户作品（攻略和游记）
  async function loadUserWorks() {
    if (!currentUser) {
      console.error('用户信息未加载完成');
      return;
    }
    
    // 加载攻略
    await loadUserGuides();
    
    // 加载游记
    await loadUserNotes();
  }
  
  // 加载用户攻略
  async function loadUserGuides() {
    const loadingElement = document.getElementById('guides-loading');
    const emptyElement = document.getElementById('guides-empty');
    const listElement = document.getElementById('guides-list');
    
    try {
      loadingElement.style.display = 'block';
      emptyElement.style.display = 'none';
      
      const response = await fetch('/guides/queryByPage', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          pageNo: 1,
          pageSize: 100,
          data: {
            visitorId: currentUser.visitorId
          }
        })
      });
      
      const result = await response.json();
      
      if (result.code === 200) {
        let guides = result.data.list || [];
        
        // 为每个攻略获取图片信息
        const guideImagePromises = guides.map(guide => {
          return fetch('/guideImages/queryByPage', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              pageNo: 1,
              pageSize: 10,
              data: {
                guideId: guide.guideId
              }
            })
          }).then(imgResponse => imgResponse.json())
            .then(imgResult => {
              if (imgResult.code === 200) {
                guide.images = imgResult.data.list || [];
              }
              return guide;
            });
        });
        
        // 等待所有图片信息加载完成
        guides = await Promise.all(guideImagePromises);
        
        if (guides.length === 0) {
          loadingElement.style.display = 'none';
          emptyElement.style.display = 'block';
        } else {
          // 渲染攻略列表
          renderGuides(guides);
          loadingElement.style.display = 'none';
        }
      } else {
        throw new Error(result.message || '加载攻略失败');
      }
    } catch (error) {
      console.error('加载攻略失败:', error);
      loadingElement.style.display = 'none';
      emptyElement.style.display = 'block';
    }
  }
  
  // 渲染攻略列表
  function renderGuides(guides) {
    const listElement = document.getElementById('guides-list');
    listElement.innerHTML = '';
    
    guides.forEach(guide => {
      // 获取攻略的第一张图片，如果没有则使用默认图片
      let imageUrl = 'https://source.unsplash.com/400x300/?travel';
      if (guide.images && guide.images.length > 0 && guide.images[0].imageUrl) {
        imageUrl = guide.images[0].imageUrl;
      }
      
      const guideElement = document.createElement('div');
      guideElement.className = 'work-item';
      guideElement.innerHTML = `
        <div class="work-image">
          <img src="${imageUrl}" alt="${guide.title}" onerror="this.src='https://source.unsplash.com/400x300/?journey'">
        </div>
        <div class="work-content">
          <div class="work-title">${guide.title}</div>
          <div class="work-meta">
            <span><i class="fas fa-map-marker-alt"></i> ${guide.destination || '未知目的地'}</span>
            <span><i class="fas fa-calendar"></i> ${formatDate(guide.createTime)}</span>
          </div>
          <div class="work-stats">
            <span><i class="fas fa-eye"></i> ${guide.viewCount || 0} 浏览</span>
            <span><i class="fas fa-heart"></i> ${guide.likeCount || 0} 点赞</span>
          </div>
          <div class="work-excerpt">${guide.content ? guide.content.substring(0, 100) + '...' : '暂无内容'}</div>
        </div>
      `;
      listElement.appendChild(guideElement);
    });
  }
  
  // 加载用户游记
  async function loadUserNotes() {
    const loadingElement = document.getElementById('notes-loading');
    const emptyElement = document.getElementById('notes-empty');
    const listElement = document.getElementById('notes-list');
    
    try {
      loadingElement.style.display = 'block';
      emptyElement.style.display = 'none';
      
      const response = await fetch('/notes/queryByPage', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          pageNo: 1,
          pageSize: 100,
          data: {
            visitorId: currentUser.visitorId
          }
        })
      });
      
      const result = await response.json();
      
      if (result.code === 200) {
        let notes = result.data.list || [];
        
        // 为每个游记获取图片信息
        const noteImagePromises = notes.map(note => {
          return fetch('/noteImages/queryByPage', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              pageNo: 1,
              pageSize: 10,
              data: {
                noteId: note.noteId
              }
            })
          }).then(imgResponse => imgResponse.json())
            .then(imgResult => {
              if (imgResult.code === 200) {
                note.images = imgResult.data.list || [];
              }
              return note;
            });
        });
        
        // 等待所有图片信息加载完成
        notes = await Promise.all(noteImagePromises);
        
        if (notes.length === 0) {
          loadingElement.style.display = 'none';
          emptyElement.style.display = 'block';
        } else {
          // 渲染游记列表
          renderNotes(notes);
          loadingElement.style.display = 'none';
        }
      } else {
        throw new Error(result.message || '加载游记失败');
      }
    } catch (error) {
      console.error('加载游记失败:', error);
      loadingElement.style.display = 'none';
      emptyElement.style.display = 'block';
    }
  }
  
  // 渲染游记列表
  function renderNotes(notes) {
    const listElement = document.getElementById('notes-list');
    listElement.innerHTML = '';
    
    notes.forEach(note => {
      // 获取游记的第一张图片，如果没有则使用默认图片
      let imageUrl = 'https://source.unsplash.com/400x300/?journey';
      if (note.images && note.images.length > 0 && note.images[0].imageUrl) {
        imageUrl = note.images[0].imageUrl;
      }
      
      const noteElement = document.createElement('div');
      noteElement.className = 'work-item';
      noteElement.innerHTML = `
        <div class="work-image">
          <img src="${imageUrl}" alt="${note.title}" onerror="this.src='https://source.unsplash.com/400x300/?travel'">
        </div>
        <div class="work-content">
          <div class="work-title">${note.title}</div>
          <div class="work-meta">
            <span><i class="fas fa-map-marker-alt"></i> ${note.location || '未知地点'}</span>
            <span><i class="fas fa-calendar"></i> ${formatDate(note.createTime)}</span>
          </div>
          <div class="work-stats">
            <span><i class="fas fa-eye"></i> ${note.viewCount || 0} 浏览</span>
            <span><i class="fas fa-heart"></i> ${note.likeCount || 0} 点赞</span>
          </div>
          <div class="work-excerpt">${note.content ? note.content.substring(0, 100) + '...' : '暂无内容'}</div>
        </div>
      `;
      listElement.appendChild(noteElement);
    });
  }
  
  // 格式化日期
  function formatDate(dateString) {
    if (!dateString) return '未知日期';
    
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
  }
  
  // 在文件末尾添加以下函数

</script>
</body>
</html>